<template>
  <div class="container-all">
    <!-- 任务信息面板 -->
    <div class="uavTask">
      <div class="untitled-page untitled-page-block layout">
        <div class="untitled-page-block1 layout">
          <div class="untitled-page-block2 layout">
            <h5 class="untitled-page-highlights layout">任务详细</h5>
          </div>
          <div class="untitled-page-flex layout">
            <div id="UavLinesTaskInfo" ref="leftForm">
              <div class="head">
                <el-button type="text" icon="el-icon-arrow-left" @click="backUavTask">返回</el-button>
              </div>
              <div class="container">
                <TaskInfo
                  :task-name="uavTaskName"
                  :info-list="uavLinesInfoList"
                  @save-route="handleSaveRoute"
                  @name-changed="handleNameChanged"
                >
                  <template #settings>
                    <RoutePlanSet 
                      ref="settingRef" 
                      @locate="locate" 
                      @drawArea="drawArea" 
                      @redrawArea="redrawArea" 
                      @editArea="editArea" 
                      @drawLine="drawLine"
                      @editLine="editLine"
                      @editLineBuffer="editLineBuffer"
                      @redrawLine="redrawLine"
                      @draw3DPlane="draw3DPlane" 
                      @edit3DPlane="edit3DPlane" 
                      @edit3DDraw="edit3DDraw"
                      @drawBuildingArea="drawBuildingArea"
                      @editBuildingArea="editBuildingArea"
                    />
                  </template>
                </TaskInfo>
              </div>
            </div>
          </div>
          <div class="untitled-page-image1 layout"></div>
        </div>
      </div>
    </div>

    <!-- 航点详情面板 -->
    <div class="uavTaskInfo" v-if="route.query.mode==='0'">
      <div class="untitled-page untitled-page-block layout">
        <div class="untitled-page-block1 layout">
          <div class="untitled-page-block2 layout">
            <h5 class="untitled-page-highlights layout">航点详情</h5>
          </div>
          <div class="untitled-page-flex layout">
            <div id="UavLinePointInfo" ref="leftForm">
              <div class="container">
                <div class="uavLinesSet">
                  <div style="overflow:scroll;">
                    <WaypointDetails
                      :current-index="currentIndex"
                      :current-record="currentRecord"
                      :flight-path-mode-options="flightPathModeOptionsComputed"
                      :action-options="actionOptionsComputed"
                      @add-record="addRecord"
                      @del-record="delRecord"
                      @last-record="lastRecord"
                      @next-record="nextRecord"
                      @edit-record="editRecord"
                      @edit-ground-record="editGroundRecord"
                      @add-action="addAction"
                      @del-action="delAction"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="untitled-page-image1 layout"></div>
        </div>
      </div>
    </div>

    <!-- 地图容器 -->
    <div class="bigmapclass" id="GodMapPanel"></div>
    <div class="uavmapclass" id="UavMapPanel" v-if="route.query.mode==='0'"></div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { useMapOperations } from '../composables/useMapOperations'
import { useWaypointManagement } from '../composables/useWaypointManagement'
import { useAreaDrawing } from '../composables/useAreaDrawing'
import { useDataProcessing } from '../composables/useDataProcessing'
import { useUIInteractions } from '../composables/useUIInteractions'

import TaskInfo from '../components/TaskInfo.vue'
import WaypointDetails from '../components/WaypointDetails.vue'
import RoutePlanSet from '../components/RoutePlanSet.vue'

import { createActionOptions, createFlightModeOptions, createHeadingModeOptions } from '../utils/waypointUtils'
import { CameraFrustum, Tools, ViewDegree } from '../assets/cesiumFunction/SmartView'
import { v4 as uuidv4 } from 'uuid'

// 使用 composables
const route = useRoute()
const {
  GodViewer,
  UavViewer,
  frustumVisible,
  showFrustum,
  initMap,
  locate,
  SetTarget,
  areaRecord: mapCoreAreaRecord
} = useMapOperations()

const {
  recordList,
  currentIndex,
  currentRecord,
  oldSpeedOption,
  oldHeightOption,
  addRecord,
  editRecord,
  editGroundRecord,
  delRecord,
  lastRecord,
  nextRecord,
  addAction,
  delAction,
  updateWaypointHeight,
  initWaypointEntities
} = useWaypointManagement()

const {
  areaRecord: drawingAreaRecord,
  lineRecord: drawingLineRecord,
  drawArea,
  redrawArea,
  editArea,
  drawLine,
  editLine,
  editLineBuffer,
  redrawLine,
  draw3DPlane,
  edit3DPlane,
  edit3DDraw,
  drawBuildingArea,
  editBuildingArea
} = useAreaDrawing()

const {
  uavTaskName,
  uavLinesInfoList,
  initUavLinesInfoList,
  refreshLineInfo,
  saveRoutePlan,
  recordList: dataRecordList,
  areaRecord: dataAreaRecord,
  lineRecord: dataLineRecord
} = useDataProcessing()

const {
  backUavTask,
  flightPathModeOptions,
  actionOptions
} = useUIInteractions()

// 组件内部响应式数据
const mode = ref('1')
const pointRecord = ref([])
const routeSeting = ref(null)
const settingRef = ref(null)

// 计算属性
const flightPathModeOptionsComputed = computed(() => {
  return createFlightModeOptions()
})

const actionOptionsComputed = computed(() => {
  return createActionOptions()
})

// 监听器
watch(
  recordList,
  (val) => {
    refreshLineInfo(val)
    // 同步到 useDataProcessing 的 recordList
    dataRecordList.value = JSON.parse(JSON.stringify(val))
  },
  { deep: true }
)

watch(
  drawingAreaRecord,
  (val) => {
    // 同步 useAreaDrawing 的 areaRecord 到 useDataProcessing 的 areaRecord
    dataAreaRecord.value = JSON.parse(JSON.stringify(val))
  },
  { deep: true }
)

watch(
  mapCoreAreaRecord,
  (val) => {
    // 同步 useMapCore 的 areaRecord 到 useDataProcessing 的 areaRecord
    dataAreaRecord.value = JSON.parse(JSON.stringify(val))
  },
  { deep: true }
)

watch(
  drawingLineRecord,
  (val) => {
    // 同步 useAreaDrawing 的 lineRecord 到 useDataProcessing 的 lineRecord
    dataLineRecord.value = JSON.parse(JSON.stringify(val))
  },
  { deep: true }
)

watch(
  currentRecord,
  (val) => {
    updateCurrentRecordView(val)
  },
  { deep: true }
)

// 监听航点高度变化，联动更新 Cesium 中的点高度
watch(
  () => currentRecord.value?.point_fly_height,
  (newHeight, oldHeight) => {
    // 确保有有效的航点ID和高度值
    if (currentRecord.value?.uavId && newHeight !== undefined && newHeight !== null && newHeight !== oldHeight) {
      updateWaypointHeight(currentRecord.value.uavId, Number(newHeight))
    }
  }
)

// 方法
/**
 * 初始化组件
 */
const initializeComponent = async () => {
  const routeData = JSON.parse(route.query.data)
  initUavLinesInfoList(routeData)
  await initMap(routeData)
  uavTaskName.value = routeData.wayline_name
  setupRouteSettings(routeData)
  setupEventListeners()
}

/**
 * 设置路由设置
 */
const setupRouteSettings = (routeData) => {
  routeSeting.value = {
    mode: routeData.waylineType,
    heightMode: routeData.heightMode,
    height: routeData.globalFlyHeight,
    linesSpeedOption: routeData.globalFlySpeed,
  }
  
  const positions = routeData.wayline_folder.uav_positions || []
  recordList.value = positions
  // 同步到 useDataProcessing 的 recordList
  dataRecordList.value = JSON.parse(JSON.stringify(positions))
  processRecordList()
  // 初始化航点实体（从外部数据加载时创建 Cesium 实体）
  initWaypointEntities()
}

/**
 * 处理记录列表
 */
const processRecordList = () => {
  recordList.value.forEach((uav, uavIndex) => {
    const uavPosition = Cesium.Cartesian3.fromDegrees(
      Number(uav.point_coordinate.longitude),
      Number(uav.point_coordinate.latitude),
      Number(uav.point_fly_height),
    )

    let flightPathMode = uav.flightPathMode || 1
    let headingMode = uav.headingMode || 0
    let point_fly_speed = Number(uav.point_fly_speed) || Number(routeSeting.value.linesSpeedOption)
    
    oldSpeedOption.value = Number(routeSeting.value.linesSpeedOption)
    currentIndex.value = 1
    currentRecord.value = recordList.value[0]
  })
}

/**
 * 设置事件监听器
 */
const setupEventListeners = () => {
  // 注意：在 Vue3 中需要替换 $bus 为 mitt 或其他事件总线
  // $bus.$on('getRoutePlanSetting', handleRoutePlanSetting)
  // $bus.$on('refreshPointSeq', handleRefreshPointSeq)
}

/**
 * 处理路由规划设置
 */
const handleRoutePlanSetting = (routeSetingData) => {
  let postSpeed = routeSetingData.linesSpeedOption
  if (oldSpeedOption.value != postSpeed) {
    for (let recordIndex in recordList.value) {
      if (recordList.value[recordIndex].point_fly_speed == oldSpeedOption.value) {
        recordList.value[recordIndex].point_fly_speed = postSpeed
      }
    }
  }

  let postHeight = routeSetingData.height
  if (oldHeightOption.value != postHeight) {
    for (let recordIndex in recordList.value) {
      if (recordList.value[recordIndex].point_fly_height == oldHeightOption.value) {
        recordList.value[recordIndex].point_fly_height = postHeight
      }
    }
  }

  routeSeting.value = routeSetingData
  oldSpeedOption.value = postSpeed
  oldHeightOption.value = postHeight
}

/**
 * 处理刷新点序列
 */
const handleRefreshPointSeq = (pointList) => {
  let temp = recordList.value[Number(pointList[0])]
  recordList.value[Number(pointList[0])] = recordList.value[Number(pointList[1])]
  recordList.value[Number(pointList[1])] = temp
  console.log("实际点")
  console.log(recordList.value[Number(pointList[0])])
  console.log(recordList.value[Number(pointList[1])])
}

/**
 * 处理名称变化
 */
const handleNameChanged = (newName) => {
  uavTaskName.value = newName
}

/**
 * 处理保存路由
 */
const handleSaveRoute = () => {
  if (settingRef.value && settingRef.value.form) {
    saveRoutePlan(settingRef.value.form)
  }
}

/**
 * 更新当前记录视图
 */
const updateCurrentRecordView = (val) => {
  if (!val || !val.point_coordinate || !val.point_actions || !val.point_actions.length) {
    return
  }

  let observer = Cesium.Cartesian3.fromDegrees(
    val.point_coordinate.longitude, 
    val.point_coordinate.latitude, 
    val.point_coordinate.altitude?val.point_coordinate.altitude:100
  )

  let target

  // 首先检查是否存在 action_type == 40，如果存在则直接使用其 point_ground 坐标
  let action40 = null
  for (let i = 0; i < val.point_actions.length; i++) {
    if (val.point_actions[i].action_type === 40) {
      action40 = val.point_actions[i]
      break
    }
  }

  if (action40 && action40.point_ground) {
    // 如果存在 action_type == 40，直接使用其 point_ground 坐标
    target = Cesium.Cartesian3.fromDegrees(
      action40.point_ground.longitude,
      action40.point_ground.latitude,
      action40.point_ground.altitude?action40.point_ground.altitude:0
    )
  } else {
    // 如果不存在 action_type == 40，则使用 action_type == 6 和 action_type == 7 的逻辑
    // 遍历 point_actions 查找 action_type == 6 (航向角) 和 action_type == 7 (俯仰角)
    let headingAngle = null // 航向角
    let pitchAngle = null // 俯仰角
    
    for (let i = 0; i < val.point_actions.length; i++) {
      const action = val.point_actions[i]
      if (action.action_type === 6) {
        headingAngle = action.action_param_value
      } else if (action.action_type === 7) {
        pitchAngle = action.action_param_value
      }
    }

    // 如果没有找到 action_type == 6，默认使用航向方向（计算从上一个航点到当前航点的航向）
    if (headingAngle === null) {
      // 尝试计算从上一个航点到当前航点的航向
      // currentIndex 从1开始，所以当前航点是 recordList[currentIndex - 1]，上一个航点是 recordList[currentIndex - 2]
      if (currentIndex.value > 1 && recordList.value.length >= currentIndex.value - 1) {
        const prevRecord = recordList.value[currentIndex.value - 2]
        if (prevRecord && prevRecord.point_coordinate) {
          const prevPoint = Cesium.Cartesian3.fromDegrees(
            prevRecord.point_coordinate.longitude,
            prevRecord.point_coordinate.latitude,
          )
          headingAngle = Tools.HeadingPointToPoint(prevPoint, observer)
        } else {
          headingAngle = 0
        }
      } else {
        // 如果没有上一个航点，使用默认值0
        headingAngle = 0
      }
    }

    // 如果没有找到 action_type == 7，默认垂直向下90°
    if (pitchAngle === null) {
      pitchAngle = -90
    }

    // 根据航向角和俯仰角计算目标点
    // 创建 ViewDegree 对象（方位角朝北为0，顺时针为正值；俯仰角水平为0，向下为负值）
    const viewDegree = new ViewDegree(headingAngle, pitchAngle)
    
    // 计算距离，使目标点在地面上
    // 如果俯仰角是-90°（垂直向下），距离就是观察点的高度
    // 对于其他角度，需要根据俯仰角计算距离
    const observerHeight = val.point_coordinate.altitude?val.point_coordinate.altitude:100
    let distance
    
    if (Math.abs(pitchAngle + 90) < 0.01) {
      // 垂直向下，距离就是高度
      distance = observerHeight
    } else {
      // 根据俯仰角计算距离，使目标点在地面上
      // distance = height / sin(|pitch|)
      const pitchRad = Cesium.Math.toRadians(Math.abs(pitchAngle))
      distance = observerHeight / Math.sin(pitchRad)
    }

    // 使用 Tools.GetPositionAlongViewDegree 计算目标点
    target = Tools.GetPositionAlongViewDegree(observer, viewDegree, distance)
    
    // 确保目标点在地面上（高度为0或从地形获取）
    const targetCartographic = Cesium.Cartographic.fromCartesian(target)
    targetCartographic.height = 0 // 设置为地面高度
    target = Cesium.Cartesian3.fromRadians(
      targetCartographic.longitude,
      targetCartographic.latitude,
      targetCartographic.height
    )
  }

  
  let frustum = CameraFrustum.CreateFrustumByTarget(GodViewer.value, observer, target, 55, 1.33, null, 2)
  
  frustumVisible.value = true
  
  // 检查 showFrustum 是否已初始化（仅在模式 0 时初始化）
  if (showFrustum.value && route.query.mode === '0') {
    showFrustum.value.UpdateFrustum(frustum)

    setTimeout(() => {
      if (showFrustum.value && showFrustum.value.frustum) {
        showFrustum.value.frustum.SetUavViewer(UavViewer.value, "UavMapPanel")
      }
    }, 500)

    setupUavViewerClickHandler(observer)
  }
}

/**
 * 设置UAV查看器点击处理器
 */
const setupUavViewerClickHandler = (observer) => {
  if (!UavViewer.value || !showFrustum.value) {
    return
  }
  
  const handler_suv = new Cesium.ScreenSpaceEventHandler(UavViewer.value.scene.canvas)
  handler_suv.setInputAction((event) => {
    const canvas = UavViewer.value.canvas
    const x_factor = event.position.x / canvas.width
    const y_factor = event.position.y / canvas.height
    
    if (!showFrustum.value || !showFrustum.value.frustum) return
    
    const position = showFrustum.value.frustum.ShowPosition(x_factor, y_factor)
    SetTarget(observer, position)
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

/**
 * 生成ID
 */
const generateId = () => {
  return uuidv4()
}

/**
 * 清理资源
 */
const cleanup = () => {
  try {
    // 清理 Cesium viewer 的实体（不销毁 viewer，因为 useMapCore 是单例）
    if (GodViewer.value && GodViewer.value.entities) {
      GodViewer.value.entities.removeAll()
    }
    
    // 清理 UavViewer 的实体
    if (UavViewer.value && UavViewer.value.entities) {
      UavViewer.value.entities.removeAll()
      // 如果 UavViewer 有 destroy 方法，可以销毁它（因为它是独立的）
      if (UavViewer.value.destroy) {
        UavViewer.value.destroy()
      }
      UavViewer.value = null
    }
    
    // 清理其他资源
    if (showFrustum.value) {
      showFrustum.value = null
    }
    
    // 清理记录列表
    recordList.value = []
    
    // 注意：在 Vue3 中需要替换 $bus 为 mitt 或其他事件总线
    // $bus.$off(['openPoiList', 'backToSet', 'getRoutePlanSetting', 'refreshPointSeq'])
  } catch (error) {
    console.error('清理资源时出错:', error)
  }
}

// 生命周期钩子
onMounted(async () => {
  await initializeComponent()
})

onBeforeUnmount(() => {
  cleanup()
})
</script>

<style lang="scss" scoped>
.container-all {
  height: 100%;
  position: relative;
}

.uavTask {
  position: fixed;
  left: 20px;
  top: 90px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  justify-items: center;
  align-items: center;
  flex-direction: row;
}

.uavTaskInfo {
  position: fixed;
  right: 20px;
  top: 450px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  justify-items: center;
  align-items: center;
  flex-direction: row;
}

#UavLinePointInfo {
  width: 450px;
  background-color: #0b022900;

  .container {
    height: 95%;
  }

  .uavLinesSet {
    overflow: scroll;
    overflow-x: hidden;
    max-height: 450px;
  }
}

.bigmapclass {
  position: absolute;
  left: 5px;
  width: 100%;
  height: 100%;
}

.uavmapclass {
  position: absolute;
  right: 5px;
  top: 10px;
  border: 5px solid white;
  box-shadow: 5px 10px 5px 5px #0a0a0ac8;
  z-index: 3000;
  background-color: black;
  width: 533px;
  height: 300px;
}
</style>
